let template = require('art-template');
const http = require('http');
const fs = require('fs');
const path = require('path')
const url = require('url');
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
  }
//require存在延迟 导致不能实时更新内容  仍采用readfile
// const data = require('./data/data.json');
let server = http.createServer(function (req , res) { 
    console.log(__dirname);
    res.setHeader('content-type', 'charset=utf-8');
    let urlObj = url.parse(req.url,true);
    if(url.parse(req.url).pathname == '/list'){
      fs.readFile("./data/data.json",function(error,data){
        if(error)
                return console.error(error);           
        return res.end(urlObj.query.callback+'('+ JSON.stringify(data.toString())+')' ) ;
      });
      //  return res.end(JSON.stringify(data));
      //  return res.end(urlObj.query.callback + '('+JSON.stringify(data)+')');
    }
    if(url.parse(req.url).pathname == '/pos'){
        let urlObj = url.parse(req.url,true);
        let name = urlObj.query.name;
        let con = urlObj.query.con;
        let time = urlObj.query.time;      
        fs.readFile("./data/data.json",function (error , data) { 
            if(error)
                return console.error(error); 
            let cons = data.toString();
            cons = JSON.parse(cons);//转换为json
            let getStr = {"id":(cons.length+1),"name":name,"time":time,"con":con};
            cons.push(getStr);//push进数组
            let writeStr = JSON.stringify(cons);
            fs.writeFile("./data/data.json",writeStr,function(error,data){
                if(!error){
                    console.log("success write");
                    // res.end('<script>location.href = "/index.html"</script>')
   //                 console.log(urlObj);
                    //返回对象应是jquery callback(param)形式 
                    res.end(urlObj.query.callback + '('+ JSON.stringify({code: 200}) +')')
                }
            })
         })
    }
 });
 server.listen(8081,function () { 
     console.log("running.........");
  })